// ServerManager.h: interface for the CServerManager class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_SERVERMANAGER_H__4A49B5A1_053C_422B_ACBF_31E0091A5EBC__INCLUDED_)
#define AFX_SERVERMANAGER_H__4A49B5A1_053C_422B_ACBF_31E0091A5EBC__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <afxtempl.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <wspiapi.h>
#include "../Release/udt.h"
#include "../Release/EntityDefine.h"
#include "../release/CommFunc.h"

class CServerManager 
{
private:
	CString	m_strLastError;
	static CServerManager* m_pInstance; 
	UDTSOCKET m_udtServ;
	int		m_iEid;
	BOOL	m_bIsRunning; 
	HANDLE	m_hAcceptThread;
	HANDLE	m_hEventClients;
	HANDLE	m_hEventTaskInfo;
	HANDLE  m_hRecData;
public: 
	CArray<lpTerminalInfo,lpTerminalInfo> m_arrClientList; 
	CArray<lpCommandInfo,lpCommandInfo> m_arrTaskList;
	BOOL Checkconnection(); 
	BOOL Stop();
	BOOL Start(int iPort=9000);
	CString GetLastError();
	BOOL IsRunning();
	BOOL Clear();
	lpTerminalInfo FindItem(UDTSOCKET* pUDTSOCKET);
	lpCommandInfo PopTask();
	BOOL PushTask(lpCommandInfo pCommand);
	BOOL RemoveItem(int iItemIndex);
	BOOL AddItem(lpTerminalInfo pTerminalInfo);
	BOOL SendData(lpNetExchange pExchange,void* pUDTSOCKET);
	BOOL SendData(lpAccount pAcc,int iType);
	BOOL PrecessProtocal(lpNetExchange pExchange,UDTSOCKET* pUDTSOCKET);
	lpTerminalInfo FindParentByAcc(lpAccount pAcc);
	CServerManager();
	virtual ~CServerManager();
	static CServerManager* CreateInstance();
	BOOL SendTerminalLogin(lpTerminalInfo pTerminal,int iAccIndex); 
	
	void SetRevicedCB(pRevicedTerminal pFuncRevicedCB,void* pParam)
	{
		m_pParent=pParam;
		m_RevicedCB=pFuncRevicedCB;
	};
	
protected:
	static DWORD WINAPI StartServerThread(void* pParam); //Accept Thread
	static DWORD WINAPI RecveDataThread(void* pParam); //Recve Thread
	static DWORD WINAPI SendDataThread(void* pParam); //Recve Thread
private:
	//int CreateUDTSocket(UDTSOCKET& usock, int port = 0, bool rendezvous = false); 
	BOOL SendNetData(lpNetExchange pExchange,UDTSOCKET* pUDTSOCKET);
	int FindAccBy(lpTerminalInfo pTerminal, Account& acc);
	pRevicedTerminal m_RevicedCB;
	void* m_pParent;
	inline void PostRevicedCB(NetExchangeType emExchangeType,int iAccIndex,lpTerminalInfo pTerminalInfo)
	{
		if(m_RevicedCB!=NULL)
		{
			m_RevicedCB(emExchangeType,iAccIndex,pTerminalInfo,m_pParent);
		}
	};
};
#endif // !defined(AFX_SERVERMANAGER_H__4A49B5A1_053C_422B_ACBF_31E0091A5EBC__INCLUDED_)
